<?php
namespace app\user\model\user;

use app\common\model\Attach;
use app\common\model\BaseModel;
use app\user\logic\user\Account as User;
use app\common\logic\Attach as AttachLogic;
use think\model\concern\SoftDelete;

/**
 * 提问回复模型
 */
class QuestionReply extends BaseModel
{
    use softDelete;
    /**
     * 表名
     * @var string
     */
    protected $name = 'question_reply';

    /**
     * 设置自动写入时间
     * @var boolean
     */
    protected $autoWriteTimestamp = true;

    // 隐藏字段
    protected $hidden = ['delete_time'];

    /**
     * 定义字段类型
     * @var array
     */
    protected $type = [
        'id'            => 'integer',
        'question_id'   => 'integer',
        'user_id'       => 'integer',
        'reply_user_id' => 'integer',
        'create_time'   => 'integer',
        'attach'        => 'json',
    ];

    protected $append = ['attach_url'];

/* 获取器 */


/* 查询范围 */


/* 关联 */

    public function user($externalPk = 'user_id')
    {
        return $this->belongsTo(User::class, $externalPk)->bind([
            'nick_name','avatar_url'
        ]);
    }

    /**
     * 附件url获取器
     *
     * @param $value
     * @param $data
     * @return array
     */
    public function getAttachUrlAttr($value = '', $data): array
    {
        $url = [];
        if (!isset($data['attach']) || !$data['attach']) return $url;
        $attach = json_decode($data['attach'], true);
        if (!count($attach)) return $url;
        if (is_array($attach)) {
            foreach ($attach as $id) {
                $attach = Attach::find($id);
                if ($attach) {
                    if (app(AttachLogic::class)->isAudioOrVideo($attach)) {
                        $urls  = array_column($attach->fileurl, null, 'definition');
                        $url[] = $urls['OD']['play_url'];
                    } else {
                        $url[] = $attach->fileurl ?? '';
                    }
                } else {
                    $url[] = '';
                }
            }
        }

        return $url;
    }
}
